package com.hs.app.action.search;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hs.app.helper.ChangeCharset;
import com.hs.app.helper.SQLHelper;
import com.hs.app.model.CdcBiblio;
import com.hs.app.service.ISearchService;
import com.hs.core.action.BaseAction;
import com.hs.core.db.DBMgr;
import com.hs.core.db.QueryPage;
import com.hs.core.utils.SystemUtil;
@Controller  
public class SearchController  extends BaseAction {

	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(SearchController.class);
	private static Map CONSTANTMAP = new HashMap();
	private ISearchService searchService;
	@Autowired  
	public void setSearchService(ISearchService searchService) {
		this.searchService = searchService;
	}
	 @RequestMapping(value="/search/test.do")   
	    public void test(HttpServletRequest request,
					HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         DBMgr dbo = this.getDbo(request);
         String params = request.getParameter("paramnames");
         //logger.debug("params:" + params);
         SQLHelper helper = new SQLHelper();
         Map pmap = helper.initParams(request, params);
         String allsql = helper.processSql(pmap);
         logger.debug("allsql:" + allsql);
         
         
         
	         //Map treedata = getTreeStr(dbo);
	        // modelMap.addAllAttributes(treedata);
			// return new ModelAndView("app/search/abstractlist",modelMap);
			 //return new ModelAndView("app/search/searchIndex",modelMap);
			 
		 } 
	 /**
	  * 检索主页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/medtree.do")   
	   public ModelAndView stattree(HttpServletRequest request,
					HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 
		    StringBuilder builder = new StringBuilder(); 
			 
			DBMgr dbutil = this.getDbo(request);  
			List alldataList = dbutil.queryList("select * from CDC_TAGS where ISDELETE=1   order by ORDERNUM", null);
			logger.debug("alldataList:" + alldataList);
			for(int i=0;i<alldataList.size();i++){
				
				Map tag  = (Map)alldataList.get(i);
				logger.debug("map:" + tag);
				String codename = (String)tag.get("TAGNAME"); 
				String dictcode =  tag.get("ID") + "";
				String pid =  tag.get("PID") + "";
		 
					builder.append("{ id:");
					builder.append(dictcode);
					builder.append(", pId:");
					builder.append(pid);
					builder.append(", name:\"");
					builder.append(codename);
					builder.append("\"");
					if(Integer.parseInt(dictcode) <=3){
						builder.append(",chkDisabled:true"); 
					}
					builder.append("}");
					if(i != alldataList.size() - 1){
						builder.append(",");
					}
					builder.append("\n");  
				
			}
			modelMap.put("treedata", builder.toString());
	 		return new ModelAndView("app/search/medtree",modelMap);
			 
	  } 
	 /**
	  * 检索首页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/searchIndex.do")   
	    public ModelAndView searchIndex(HttpServletRequest request,
					HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
      
			return new ModelAndView("app/search/searchIndex",modelMap);
			 
		 } 
//	 /**
//	  * 异步检索
//	  * @param request
//	  * @param response
//	  * @param modelMap
//	  * @return
//	  * @throws ServletException
//	  * @throws IOException
//	  */
//	 @RequestMapping(value="/search/dosearch.do", method = RequestMethod.POST)   
//	    public void dosearch(HttpServletRequest request,
//					HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
//		 String sql = "select id,TITLE,TITLEn from SEARCHMVIEW where datatype=1";
//         String params = request.getParameter("paramnames");
//         System.out.println("params:" + params);
//         System.out.println("params:" + request.getParameter("txt_3_sel"));
//         
//		 SQLHelper helper = new SQLHelper();
//         Map pmap = helper.initParams(request, params);
//         String allsql = helper.processSql(pmap);
//         logger.debug("allsql:" + allsql);
//		 QueryPage qp = new QueryPage(request,request.getContextPath()+"/search/dosearch.do",sql,new HashMap()); 
//	     qp.query();  
//	     List datalist = qp.getDataList();
//	     StringBuffer htmlBuffer = new StringBuffer();
//	     for(int i =0;i<datalist.size();i++){
//	    	 Map rowdata = (Map)datalist.get(i);
//	    	 String idstr = rowdata.get("id")+"";
//	    	 String title = (String)rowdata.get("TITLE");
//	    	 String titlen = (String)rowdata.get("TITLEN");
//	    	 htmlBuffer.append("<tr>");
//	    	 htmlBuffer.append("<td>");
//	    	 htmlBuffer.append(idstr);
//	    	 htmlBuffer.append("</td>");
//	    	 htmlBuffer.append("<td>");
//	    	 htmlBuffer.append(title);
//	    	 htmlBuffer.append("</td>");
//	    	 htmlBuffer.append("<td>");
//	    	 htmlBuffer.append(titlen);
//	    	 htmlBuffer.append("</td>");
//	    	 htmlBuffer.append("</tr>"); 
//	     }
//	     PrintWriter out = response.getWriter();
//	     out.print(htmlBuffer.toString());
//	     out.flush();
//	     out.close();
//			//return new ModelAndView("app/search/searchIndex",modelMap); 
//		} 
	 /**
	  * 系统首页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/sysindex.do")   
    public ModelAndView sysindex(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         //DBMgr dbo = this.getDbo(request);
         //Map treedata = getTreeStr(dbo);
        // modelMap.addAllAttributes(treedata);
		 //return new ModelAndView("app/search/abstractlist",modelMap);
		 return new ModelAndView("app/search/sysindex",modelMap);
		 
	 } 
	 /**
	  * 文献检索列表形式
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/index.do")   
    public ModelAndView searchindex(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         //DBMgr dbo = this.getDbo(request);
         //Map treedata = getTreeStr(dbo);
        // modelMap.addAllAttributes(treedata);
		 //return new ModelAndView("app/search/abstractlist",modelMap);
		 return new ModelAndView("app/search/searchIndex",modelMap);
		 
	 } 
	 /**
	  * 文献检索首页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/searchcontent.do")   
	    public ModelAndView searchcontent(HttpServletRequest request,
					HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
	         //DBMgr dbo = this.getDbo(request);
	         //Map treedata = getTreeStr(dbo);
	        // modelMap.addAllAttributes(treedata);
			 //return new ModelAndView("app/search/abstractlist",modelMap);
			 return new ModelAndView("app/search/searchcontent",modelMap);
			 
		 } 
//	 /**
//	  * 检索页面
//	  * @param request
//	  * @param response
//	  * @param modelMap
//	  * @return
//	  * @throws ServletException
//	  * @throws IOException
//	  */
//	 @RequestMapping(value="/search/datalistindex.do")   
//    public ModelAndView datalistindex(HttpServletRequest request,
//				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
//         //DBMgr dbo = this.getDbo(request);
//         //Map treedata = getTreeStr(dbo);
//        // modelMap.addAllAttributes(treedata);
//		 return new ModelAndView("app/search/abstractlist",modelMap);
//		 
//	 } 
	 /**
	  * 文献检索入口
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/dosearch.do")   
    public ModelAndView dosearch(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
	 		 ModelAndView mv = new ModelAndView();  
			 mv = advSearch(request, response,modelMap); 
			 return mv;
			 
		 }  
//	 /**
//	  * 接收表单提交的参数，构成字符串
//	  * @param request
//	  * @return
//	  */
//	 private static String processParameter(HttpServletRequest request){
//		 StringBuffer buffer = new StringBuffer();
//		 Map parammap = request.getParameterMap();
//		 if(parammap != null && !parammap.isEmpty()){
//			 Set pset = parammap.entrySet();
//			 Iterator iter = pset.iterator();
//			 while(iter.hasNext()){
//				 Entry entry = (Entry)iter.next();
//				 String key = (String)entry.getKey();
//				 String[] value = (String[])entry.getValue(); 
//				// String value =  entry.getValue()+"";
//				 buffer.append("&").append(key).append("=").append(value[0]);
//			 }
//		 }
//		 return buffer.toString();
//	 }
	 
	
	 /**
	  * 全库高级检索
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  */
	 private ModelAndView advSearch(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap){  
	     Map paramMap = this.advSearchPrepare(request); 
		 String orderName = (String)paramMap.get("orderName");
		 String orderNum = (String)paramMap.get("orderNum"); 
		 String keyword = (String)paramMap.get("keyword");
		 String pidstr = (String)paramMap.get("pidstr");
		 StringBuffer allfullsql = (StringBuffer)paramMap.get("allfullsql");
		 Map conditionmap = new HashMap();
         conditionmap.put("orderName", orderName);
         conditionmap.put("orderNum", orderNum);  
         conditionmap.put("searchtype", orderNum);  
         conditionmap.put("searchtype", "advsearch");   
         conditionmap.put("keyword", keyword);
         
        
         logger.debug("allfullsql======:" + allfullsql);
		 QueryPage qp = new QueryPage(request,request.getContextPath()+"/search/dosearch.do",allfullsql.toString(),conditionmap); 
//	     
	     qp.query();  
	     String pagenum =  qp.getCurrentPageNo() + "";
	     String pagecount = qp.getPerPageCount() + "";
	     modelMap.put("pagenum", pagenum);
	     modelMap.put("pagecount", pagecount);
	     modelMap.put("pagestr", qp.getPageStr());
	     modelMap.put("datalist", qp.getDataList());
	     modelMap.put("onesql", allfullsql.toString()); 
	     modelMap.put("searchtype", "advsearch");  	  
	     modelMap.put("keyword", keyword); 
	     modelMap.put("allfullsql", allfullsql.toString()); 
		return new ModelAndView("app/search/resultlist",modelMap);
	 }
	 private Map advSearchPrepare(HttpServletRequest request){ 
		 Map paramMap = new HashMap();
		 String orderName = request.getParameter("orderName");//排序字段
		 String orderNum = request.getParameter("orderNum");//排序方式
		 String searchtype = request.getParameter("searchtype");//排序方式
		 String datatypestr = request.getParameter("datatype");//数据范围
		 String keywordstr = request.getParameter("keyword");//关键词
 		 String startyear = request.getParameter("startyear_adv");//起始年份
		 String endyear = request.getParameter("endyear_adv");//起始年份  
		 String disnamestr = request.getParameter("disnamestr");//起始年份  
		 String pidstr = request.getParameter("pidstr");//起始年份  
		 request.setAttribute("orderName", orderName); 
		 request.setAttribute("orderNum", orderNum); 
		 request.setAttribute("searchtype", searchtype); 
		 StringBuffer orderByStr = new StringBuffer(" order by ");
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		  }else{
		    	orderByStr.append("a.id").append(" desc");
		    	orderName = "a.id";
		    	orderNum = "2";
		  }
		 StringBuffer allfullsql= new StringBuffer();
		 allfullsql.append("select a.* from CDC_BIBLIO a where 1=1    ");  
 		if(StringUtils.isNotEmpty(disnamestr)){
			 String[] disnamearr = disnamestr.split(",");
			 if(null != disnamearr && disnamearr.length == 1){
				 allfullsql.append("  and  a.DISNAME='").append(disnamearr[0]).append("' ");
			 }
			 if(null != disnamearr && disnamearr.length == 2){
				 allfullsql.append("  and  (a.DISNAME='").append(disnamearr[0]).append("' ");
				 allfullsql.append("  or  a.DISNAME='").append(disnamearr[1]).append("') ");
			 }
			  
		 }
		 if(StringUtils.isNotEmpty(startyear)){
			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')>=").append("to_date("+startyear+",'yyyy') ");
		 }
		 if(StringUtils.isNotEmpty(endyear)){
			 allfullsql.append("  and  to_date(substr(a.YEARSTR,0,4),'yyyy')<=").append("to_date("+endyear+",'yyyy') ");
		 }
		 logger.debug("pidstr:" + pidstr);
         if(StringUtils.isNotEmpty(pidstr)){
        	 
        	 allfullsql.append(" and a.id in(select PID from CDC_PREHREB where ZYCYMC in(select TAGNAME from CDC_TAGS WHERE ID IN("+pidstr+")))");
        	 
         } 
 		 StringBuffer keywordbuffer = new StringBuffer();
		 //拼接sql
 		 
 		 StringBuffer conditionsql = new StringBuffer();
 		 conditionsql.append(createSql(request,"txt_1",null,keywordbuffer));
 		 conditionsql.append(createSql(request,"txt_2",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_3",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_4",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_5",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_6",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_7",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_8",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_9",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_10",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_11",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_12",null,keywordbuffer));
		 conditionsql.append(createSql(request,"txt_13",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_14",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_15",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_16",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_17",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_18",null,keywordbuffer));
//		 conditionsql.append(createSql(request,"txt_19",null,keywordbuffer));
		 System.out.println("conditionsql:" + conditionsql);
		 if(!"".equals(conditionsql.toString())){ 
			 allfullsql.append(" and ");
			 allfullsql.append("(");
			 allfullsql.append(conditionsql.substring(4,conditionsql.length()));
			 allfullsql.append(") ");
		 }
		 allfullsql.append(orderByStr); 
		//翻页时使用从页面传过来的关键词
		 if("".equals(keywordbuffer.toString())&&StringUtils.isNotEmpty(keywordstr)){
			 keywordbuffer.append(keywordstr);
		 }
//		 
		 String keyword = keywordbuffer.toString(); 
	     if(keyword.endsWith("|")){
	    	 keyword = keyword.substring(0,keyword.length()-1);
	     }
	     
	     paramMap.put("allfullsql", allfullsql); 
	     paramMap.put("orderName", orderName);
	     paramMap.put("orderNum", orderNum); 
	     paramMap.put("keyword", keyword); 
		 return paramMap;
	 }

	 private String createSql(HttpServletRequest request,String cname,StringBuffer buffer,StringBuffer keywordbuffer){
		 StringBuffer sqlbuffer = new StringBuffer();
		 //值
		 String c_value = cname+"_value";
		 //逻辑关系，并且 或者
		 String c_logical = cname+"_logical";
		 //字段的名字
		 String c_sel = cname+"_sel";
		 //精确或模糊
		 String c_special = cname+"_special";
		 
		 String cvalue = request.getParameter(c_value);
		 String clogical = request.getParameter(c_logical);
		 String csel = request.getParameter(c_sel);
		 String cspecial = request.getParameter(c_special);
		 
		 String logicalname = "";
		 
		 String colname = (String)CONSTANTMAP.get(csel);
//		 if(null != colname){
//			 if("1".equals(clogical)){
//				 logicalname = " OR ";
//				 
//			 }else{
//				 logicalname = " AND ";
//			 }
//			// buffer.append(colname ).append("“").append(cvalue).append("”&nbsp;").append(logicalname).append("&nbsp;");
//			 keywordbuffer.append(cvalue).append("|");
//		 }
		 if(null != cvalue)
			 keywordbuffer.append(cvalue).append("|");
		 request.setAttribute(c_value, cvalue);
		 request.setAttribute(c_logical, c_logical);
		 request.setAttribute(c_sel, c_sel);
		 request.setAttribute(c_special, c_special);
		 //logger.debug("value:::" + clogical + "," + csel + "," + cvalue + "," + cspecial);
//		 if(StringUtils.isEmpty(cspecial))
//			 cspecial = "1";//默认为模糊检索
		 if(null == cvalue || StringUtils.isEmpty(cvalue)){//查询条件为空时返回空
			 return "";
		 }
		 logger.debug("clogical:" + clogical);
		 logger.debug("c_sel:" + c_sel);
		 if("0".equals(clogical)){
			 //0 and 关系  1：或者关系
			 sqlbuffer.append(" and "); 
		 }else if("1".equals(clogical)){
			 //0 and 关系  1：或者关系
			 sqlbuffer.append(" or "); 
		 }else{
			 sqlbuffer.append(" and "); 
		 }
		 sqlbuffer.append("lower(").append(csel).append(")");
		 if("0".equals(cspecial)){
			 //0 精确  1：模糊
			 sqlbuffer.append(" =lower('"); 
			 sqlbuffer.append(cvalue.trim());
			 sqlbuffer.append("')");
		 }
		 if("1".equals(cspecial)){
			//0 精确  1：模糊
			 sqlbuffer.append(" like '%'||lower('"); 
			 sqlbuffer.append(cvalue.trim());
			 sqlbuffer.append("')||'%'");
		 }
		 return sqlbuffer.toString();
	 }
	
	
	 
	 /**
	  * 数据导出
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/resultexport.do", method = RequestMethod.GET)   
     public ModelAndView resultexport(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		  String pid = request.getParameter("pid");
		  if(StringUtils.isNotEmpty(pid)){ 
			  CdcBiblio obj = (CdcBiblio)this.searchService.findByID(CdcBiblio.class, new Long(pid));
			  modelMap.put("obj", obj);
		  }
		  return new ModelAndView("app/search/detail",modelMap);
		 
	 }
	 /**
	  * 查看详细题录信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/viewdetail.do", method = RequestMethod.GET)   
     public ModelAndView viewdetail(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		  String pid = request.getParameter("pid");
		  if(StringUtils.isNotEmpty(pid)){ 
			  CdcBiblio obj = (CdcBiblio)this.searchService.findByID(CdcBiblio.class, new Long(pid));
			  modelMap.put("obj", obj);
		  }
		  return new ModelAndView("app/search/detail",modelMap);
		 
	 }
//	
//	 private static String cutStr(String str){
//		 if(str.lastIndexOf(',') != -1){
//			 str = str.substring(0, str.length()-1);
//		 }
//		 return str;
//	 }
//	 
	 static {
		 CONSTANTMAP.put("TITLE","标题");
		 CONSTANTMAP.put("TITLEN","标题");
		 CONSTANTMAP.put("PERIODICALNAME","刊名");
		 CONSTANTMAP.put("PERIODICALNAMEENG","刊名");
		 CONSTANTMAP.put("BOOKNAME","书籍名称");
		 CONSTANTMAP.put("AUTHOR","作者");
		 CONSTANTMAP.put("AUTHOREN","作者");
		 CONSTANTMAP.put("AUTHORUNIT","作者单位");
		 CONSTANTMAP.put("AUTHORADDRESS","作者通讯地址");
		 CONSTANTMAP.put("KEYWORD","关键词");
		 CONSTANTMAP.put("KEYWORDENG","关键词");
		 CONSTANTMAP.put("SUBJECTWORD","主题词");
		 CONSTANTMAP.put("SUBJECTWORDENG","主题词");
		 CONSTANTMAP.put("ABSTRACT","摘要");
		 CONSTANTMAP.put("ABSTRACTENG","摘要");
		 CONSTANTMAP.put("ORIGINALTEXT","原文文本");
		 CONSTANTMAP.put("LANGUAGE","语种");
		 CONSTANTMAP.put("DOCUMENTTYPE","文献类型");
		 CONSTANTMAP.put("CLASSNO","分类号");
		 CONSTANTMAP.put("FUNDSTR","资助情况");
		 CONSTANTMAP.put("YEARSTR","年份");
		 CONSTANTMAP.put("VOLUME","卷");
		 CONSTANTMAP.put("PERIOD","期");
		 CONSTANTMAP.put("PAGENO","页码");
		 CONSTANTMAP.put("VOLUMESECTION","卷册章节");
		 CONSTANTMAP.put("FUNDTYPE","资助类别");
		 CONSTANTMAP.put("COMFROM","文献来源");
		 CONSTANTMAP.put("AREASTR","国家\\省市");
		 CONSTANTMAP.put("CWNUM","参文数");
		 CONSTANTMAP.put("ISSNSTR","ISSN编号");
		 CONSTANTMAP.put("CONTRYCODE","国内代码");
		 CONSTANTMAP.put("CODESTR","内部代码");
		 CONSTANTMAP.put("PUBLISHAREA","出版地");
		 CONSTANTMAP.put("IMPRESSWORD","特征词");
		 CONSTANTMAP.put("UPDATEDATE","更新日期");
		 CONSTANTMAP.put("AUTHORABSTRACT","著者文摘");
		 CONSTANTMAP.put("FUNDNAME","基金");
		 CONSTANTMAP.put("CASTR","CA");
		 CONSTANTMAP.put("USERSUBJECT","人名主题");
		 CONSTANTMAP.put("TCMNAME","中医病名");
		 CONSTANTMAP.put("BOOKVERSION","书籍版本");
		 CONSTANTMAP.put("INPUTUSER","录入人"); 
		 CONSTANTMAP.put("BOOKCD","朝代"); 
	 }
		@RequestMapping("/search/exportAllData.do")   
		public ModelAndView exportAllData(HttpServletRequest request,
				HttpServletResponse response) throws Exception { 
			try  {
				String ids = request.getParameter("ids");
				if(StringUtils.isEmpty(ids)){
					return null;
				}else{
					ids = ids.substring(0,ids.length()-1);
				}
				String path = this.exportTxtData(ids);
				System.out.println("message::" + path );
				//  path是指欲下载的文件的路径。 
 				File file  =   new  File(path);
				String filename  =  file.getName();
				int fileLength = (int)file.length();
				int                 length   = 0;
		        ServletOutputStream op       = response.getOutputStream();
		        ServletContext      context  = request.getSession().getServletContext();
		        String              mimetype = context.getMimeType( filename );
		        byte[]   byteContents   =   new   byte[fileLength];   
		        FileInputStream fis   =   new   FileInputStream(file);   
		        int   retcd   =   fis.read(byteContents);   
		        fis.close();    
		        logger.debug("mimetype:" + mimetype);
		        response.setContentType(mimetype == null?"text/plain":mimetype );
		        response.setContentLength( retcd );
		        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
		        op.write(byteContents,0,retcd); 
		        op.close();
	    }  catch  (IOException ex) {
	        ex.printStackTrace();
	    }
			return null;  
		} 
		/**
		 * 生成题录数据文件（TXT）
		 * @return 生成的文件的路径
		 */
		public String exportTxtData(String rids){
			String message = "false";
			 try {
				 String tempFilepath = SystemUtil.getWebappRoot().toString();
				 tempFilepath = tempFilepath.replace("\\", "/") + "/temp";
				 System.out.println("tempFilepath::" + tempFilepath );
				 File tempfile = new File(tempFilepath);
				 if(!tempfile.exists()){
					 tempfile.mkdirs();
				 }
				 String destfile = tempFilepath + "/" + "export"+System.currentTimeMillis()+".txt";
				 FileOutputStream outSTr = null;      
				 BufferedOutputStream Buff = null;    
				      
				 String tab = "  ";      
				 String enter = "\r\n";      
				 List  accList = DBMgr.getDbUtilInst().queryList("select * from CDC_BIBLIO where id in("+rids+") order by id",null);
	
				   StringBuffer write ;      
				    try {      
				        outSTr = new FileOutputStream(new File(destfile));      
				        Buff = new BufferedOutputStream(outSTr);      
				        for(int i=0; i<accList.size(); i++){
							Map data = (Map)accList.get(i);      
				            write = new StringBuffer(); 
				            String temp0 = null2str((String)data.get("DISNAME"));
				            if(!"".equals(temp0))
				            	write.append("病名:"+temp0+enter); 
				            String temp1 = null2str((String)data.get("CLASSNO"));
				            if(!"".equals(temp1))
				            	write.append("分类号:"+temp1+enter); 
				            String temp2 = null2str((String)data.get("TITLE"));
				            if(!"".equals(temp2))
				            	write.append("标题:"+temp2+enter); 
				            String temp3 = null2str((String)data.get("AUTHOR"));
				            if(!"".equals(temp3))
							write.append("作者:"+temp3+enter);
				            String temp4 = null2str((String)data.get("AUTHORUNIT"));
				            if(!"".equals(temp4))
				            	write.append("作者单位:"+temp4+enter);
				            String temp5 = null2str((String)data.get("AREASTR"));
				            if(!"".equals(temp5))
							write.append("国家\\省市:"+temp5+enter);
				            String temp6 = null2str((String)data.get("CWNUM"));
				            if(!"".equals(temp6))
				            	write.append("参文数:"+temp6+enter);
				            String temp7 = null2str((String)data.get("PERIODICALNAME"));
				            if(!"".equals(temp7))
							    write.append("刊名:"+temp7+enter);
				            String temp8 = null2str((String)data.get("YEARSTR"));
				            if(!"".equals(temp8))
				            	write.append("年份:"+temp8+enter);
				            String temp9 = null2str((String)data.get("VOLUME"));
				            if(!"".equals(temp1))
							write.append("卷:"+temp9+enter);
				            String temp10 = null2str((String)data.get("PERIOD"));
				            if(!"".equals(temp10))
							write.append("期:"+temp10+enter); 
				            String temp11 = null2str((String)data.get("PAGENO"));
				            if(!"".equals(temp11))
				            	write.append("页码:"+temp11+enter);
				            String temp12 = null2str((String)data.get("ISSNSTR"));
				            if(!"".equals(temp12))
				            	write.append("ISSN:"+temp12+enter); 
				            String temp13 = null2str((String)data.get("CONTRYCODE"));
				            if(!"".equals(temp13)) 
				            	write.append("国别:"+temp13+enter);
				            String temp14 = null2str((String)data.get("CODESTR"));
				            if(!"".equals(temp14))  
				            	write.append("地区:"+temp14+enter);
				            String temp15 = null2str((String)data.get("PUBLISHAREA"));
				            if(!"".equals(temp15)) 
							write.append("出版地:"+temp15+enter);
				            String temp16 = null2str((String)data.get("KEYWORD"));
				            if(!"".equals(temp16)) 
							write.append("关键词:"+temp16+enter);
				            String temp17 = null2str((String)data.get("SUBJECTWORD"));
				            if(!"".equals(temp17)) 
							write.append("主题词:"+temp17+enter);
				            String temp18 = null2str((String)data.get("IMPRESSWORD"));
				            if(!"".equals(temp18)) 
							write.append("特征词:"+temp18+enter);
				             
				             
				            String temp21 = null2str((String)data.get("ABSTRACT"));
				            if(!"".equals(temp21)) 
							write.append("摘要:"+temp21+enter);
				            String temp22 = null2str((String)data.get("AUTHORABSTRACT"));
				            if(!"".equals(temp22)) 
							write.append("著者文摘:"+temp22+enter);
				            String temp23 = null2str((String)data.get("DOCUMENTTYPE"));
				            if(!"".equals(temp23)) 
							write.append("文献类型:"+temp23+enter);
				            String temp24 = null2str((String)data.get("FUNDNAME"));
				            if(!"".equals(temp24)) 
							write.append("基金:"+temp24+enter);
				            String temp25 = null2str((String)data.get("LANGUAGE"));
				            if(!"".equals(temp25)) 
							write.append("语种:"+temp25+enter);
				            String temp26 = null2str((String)data.get("USERSUBJECT"));
				            if(!"".equals(temp26)) 
							write.append("人名主题:"+temp26+enter);
				            String temp27 = null2str((String)data.get("CASTR"));
				            if(!"".equals(temp27)) 
							write.append("CA:"+temp27+enter);
				            
				             
				            
				            String temp31 = null2str((String)data.get("VOLUMESECTION"));
				            if(!"".equals(temp31)) 
							write.append("卷册章节:"+temp31+enter);
				            String temp32 = null2str((String)data.get("BOOKVERSION"));
				            if(!"".equals(temp32)) 
							write.append("书籍版本:"+temp32+enter);
				            String temp33 = null2str((String)data.get("INPUTUSER"));
				            if(!"".equals(temp33)) 
							write.append("录入人:"+temp33+enter);
				            String temp34 = null2str((String)data.get("INPUTDATE"));
				            if(!"".equals(temp34)) 
						    write.append("录入日期:"+temp34+enter); 
				             
				            write.append(enter);          
				            Buff.write(write.toString().getBytes("UTF-8")); 
				            
				        }             
				        Buff.flush();      
				        Buff.close();      
				  } catch (Exception e) {      
				        e.printStackTrace();      
				    } finally {      
				        try {      
				           Buff.close();      
				            outSTr.close();      
				        } catch (Exception e) {      
				           e.printStackTrace();      
				        }      
				    }       
					 message = destfile;
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			return message;
			
		}
		private String null2str(String content){
			if(null == content || "null".equalsIgnoreCase(content)){
				return "";
			}
			return content;
		}
}
